﻿
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace UtilsBase
{
    public static class UtilsMachineInfo
    {
        static string deviceId = "";


        //public static string GetNetCardMAC()
        //{
        //    try
        //    {
        //        string stringMAC = "";
        //        ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //        ManagementObjectCollection MOC = MC.GetInstances();
        //        foreach (ManagementObject MO in MOC)
        //        {
        //            if ((bool)MO["IPEnabled"] == true)
        //            {
        //                stringMAC += MO["MACAddress"].ToString();

        //            }
        //        }
        //        return stringMAC;
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //}
        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        public static string GetIP(HttpContext httpContext)
        {
            try
            {
                HttpContextAccessor context = new HttpContextAccessor();
                var IP = context.HttpContext?.Connection.RemoteIpAddress.ToString();
                return IP;
            }
            catch
            {

            }
            return "";
        }

        static string gatewaycode = "";
        /// <summary>
        /// 网关编码
        /// </summary>
        /// <returns></returns>
        public static string getGateWayMachineCode()
        {
            //先读取配置文件,新版本key,value
            if (gatewaycode == "")
            {
                gatewaycode = UtilsFileHelper.readDeviceCode("gatewaycode.txt", "code");
            }

            //补充旧版本value
            //先读取配置文件
            if (gatewaycode == "")
            {
                gatewaycode = UtilsFileHelper.readDeviceCode("gatewaycode.txt");
            }
            return gatewaycode;
        }

        static string _ServerMachineCode = "";
        /// <summary>
        /// 服务器编码
        /// </summary>
        /// <returns></returns>
        public static string getServerMachineCode()
        {
            //先读取配置文件
            if (_ServerMachineCode == "")
            {
                _ServerMachineCode = UtilsFileHelper.readDeviceCode("servercode.txt", "code");
                Console.WriteLine("serverCode:" + _ServerMachineCode);
            }
            return _ServerMachineCode;
        }

        static string _ServerMachineKey = "";
        /// <summary>
        /// 服务器key
        /// </summary>
        /// <returns></returns>
        public static string getServerMachineKey()
        {
            //先读取配置文件
            if (_ServerMachineKey == "")
            {
                _ServerMachineKey = UtilsFileHelper.readDeviceCode("servercode.txt", "key");
            }
            return _ServerMachineKey;
        }
        /// <summary>
        /// 获取设备id
        /// </summary>
        /// <returns></returns>
        //public static string getMachineId()
        //{
        //    //return "32c050000c0048080145c905308a1f8e";
        //    if (!string.IsNullOrEmpty(deviceId))
        //    {
        //        return deviceId;
        //    }

        //    //树梅派的方法 Raspberry
        //    try
        //    {
        //        deviceId = new UtilsRaspberryPiMachine().getRaspberryPiDeviceId();
        //        if (!string.IsNullOrWhiteSpace(deviceId))
        //        {
        //            return deviceId;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Console.WriteLine("树梅派 设备标识读取失败" + ex);
        //    }

        //    // 香橙派系统ubuntu 的方法
        //    try
        //    {

        //        deviceId = new UtilsOrangePiMachine().getOrangePiDeviceId();
        //        if (!string.IsNullOrWhiteSpace(deviceId))
        //        {
        //            return deviceId;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Console.WriteLine(" 香橙派 设备标识读取失败" + ex);
        //    }

        //    if (string.IsNullOrWhiteSpace(deviceId))
        //    {
        //        //如果没有，就读取设备code
        //        deviceId = getGateWayMachineCode();
        //        if (!string.IsNullOrWhiteSpace(deviceId))
        //        {
        //            return deviceId;
        //        }
        //    }
        //    return "empty";
        //}
        public static string getLocalIP()
        {

            return NetworkInterface.GetAllNetworkInterfaces()
                    .Select(p => p.GetIPProperties())
                    .SelectMany(p => p.UnicastAddresses)
                    .FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address.ToString();
        }
        /// <summary>
        /// 获取本机所有IP
        /// </summary>
        /// <returns></returns>
        public static List<string> getLocalIPS()
        {
            List<string> ips = new List<string>();

            NetworkInterface[] list = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface item in list)
            {
                //if (item.NetworkInterfaceType == NetworkInterfaceType.Ethernet&& item.OperationalStatus == OperationalStatus.Up)
                //{
                foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                    {

                        ips.Add(ip.Address.ToString());
                        //  ips.Add(ip.Address.ToString() + "-" + item.NetworkInterfaceType);
                    }
                    //else
                    //{
                    //    ips.Add(ip.Address.ToString());
                    //}
                }
                // }
            }
            return ips;
        }
        /// <summary>
        /// 取系统名
        /// </summary>
        /// <returns></returns>
        public static string getSystemNameAndVersion()
        {
            //bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            //使用OSDescription获取操作系统版本信息，如可能值为Microsoft Windows 10.0.10586
            return RuntimeInformation.OSDescription;

        }
        /// <summary>
        /// 每次启动生成一个识别码，分辨是否系统重启过
        /// </summary>
        public static string SystemStartCode = "";
        /// <summary>
        /// 每次启动生成一个识别码，分辨是否系统重启过
        /// </summary>
        public static string getSystemStartCode()
        {
            if (SystemStartCode == "")
            {
                SystemStartCode = Guid.NewGuid().ToString();
            }
            return SystemStartCode;
        }
        /// <summary>
        /// 开发环境白名单
        /// </summary>
        /// <returns></returns>
        public static string getRumEnvironment()
        {

            ///development
            ///test
            ///product
            string myEnvironmentValue = environment_value;
            if (!string.IsNullOrWhiteSpace(myEnvironmentValue))
            {
                return myEnvironmentValue.Trim();
            }

            //window
            myEnvironmentValue = Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Machine);//获取环境变量
            if (!string.IsNullOrWhiteSpace(myEnvironmentValue))
            {
                Console.WriteLine("myEnvironmentValue_window:" + myEnvironmentValue);
                return myEnvironmentValue.Trim();
            }
            //linux
            myEnvironmentValue = Environment.GetEnvironmentVariable(key);//获取环境变量
            if (!string.IsNullOrWhiteSpace(myEnvironmentValue))
            {
                Console.WriteLine("myEnvironmentValue_linux:" + myEnvironmentValue);
                return myEnvironmentValue.Trim();
            }


            if (string.IsNullOrEmpty(environment_value))
            {
                return "development";
            }

            Console.WriteLine("无环境变量");
            return "";



        }
        public static List<string> getActiveMacAddress(string separator = "-")
        {
            try
            {
                //本地计算机网络连接信息
                IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
                //获取本机电脑名
                var HostName = computerProperties.HostName;
                //获取域名
                var DomainName = computerProperties.DomainName;
                //获取本机所有网络连接
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

                var macAddress = new List<string>();
                if (nics == null || nics.Length < 1)
                {
                    //Debug.WriteLine("  No network interfaces found.");
                    return macAddress;
                }

                //Debug.WriteLine("  Number of interfaces .................... : {0}", nics.Length);
                foreach (NetworkInterface adapter in nics.Where(c =>
                    c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))
                {
                    IPInterfaceProperties properties = adapter.GetIPProperties();

                    var unicastAddresses = properties.UnicastAddresses;
                    if (unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork))
                    {
                        var address = adapter.GetPhysicalAddress();

                        if (string.IsNullOrEmpty(separator))
                        {
                            macAddress.Add(address.ToString());
                        }
                        else
                        {
                            var MACIp = "";
                            byte[] bytes = address.GetAddressBytes();
                            for (int i = 0; i < bytes.Length; i++)
                            {
                                MACIp += bytes[i].ToString("X2");

                                if (i != bytes.Length - 1)
                                {
                                    MACIp += separator;
                                }
                            }

                            macAddress.Add(MACIp);
                        }
                    }
                }
                return macAddress;
            }
            catch (Exception ex)
            {
                //new UtilsFileHelper().log_WriteMessageAppend("error", ex.ToString());
                return null;
            }
        }
        //配置系统环境变量
        const string key = "myEnvironmentValue";
        public static string environment_value = "";
        /// <summary>
        ///  //设置环境变量
        ///development
        ///test
        ///product
        /// </summary>
        /// <param name="arg"></param>
        public static void setEnvironment(string[] arg)
        {
            try
            {
                if (arg.Length > 0)
                {
                    //设置特别环境变量
                    environment_value = arg[0];

                }
                else
                {
                    //不设置特别环境变量

                    //window
                    string myEnvironmentValue = Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Machine);//获取环境变量
                    Console.WriteLine("window 环境变量EnvironmentValue:" + myEnvironmentValue);

                    //linux
                    if (string.IsNullOrEmpty(myEnvironmentValue))
                    {
                        environment_value = Environment.GetEnvironmentVariable(key);//获取环境变量
                        Console.WriteLine("linux 环境变量EnvironmentValue:" + environment_value);
                    }

                }
                if (string.IsNullOrEmpty(environment_value))
                {
                    environment_value = "development";
                }
                Console.WriteLine("setEnvironment: " + environment_value);
                //window
                //set
                //Environment.SetEnvironmentVariable(key, environment_value, EnvironmentVariableTarget.Machine);
                //get
                //string myEnvironmentValue = Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.Machine);//获取环境变量
                //Console.WriteLine("myEnvironmentValue_window:" + myEnvironmentValue);

                //linux
                //set
                //Environment.SetEnvironmentVariable(key, environment_value);
                //get
                //myEnvironmentValue = Environment.GetEnvironmentVariable(key);//获取环境变量
                //Console.WriteLine("设置环境变量myEnvironmentValue:" + environment_value);
            }
            catch (Exception ex)
            {
                Console.WriteLine("环境变量设置失败");
                Console.WriteLine(ex);
            }
        }

      
    }

}

